package com.qf.gh.service.impl;

import com.qf.gh.dao.CartDao;
import com.qf.gh.dao.OrderDao;
import com.qf.gh.dao.OrderDetailDao;
import com.qf.gh.dao.impl.CartDaoImpl;
import com.qf.gh.dao.impl.OrderDaoImpl;
import com.qf.gh.dao.impl.OrderDetailDaoImpl;
import com.qf.gh.domain.Cart;
import com.qf.gh.domain.Order;
import com.qf.gh.domain.OrderDetail;
import com.qf.gh.service.CartService;
import com.qf.gh.service.OrderService;
import com.qf.gh.utils.RandomUtils;
import com.qf.gh.utils.TxUtils;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.Date;
import java.util.List;

public class OrderServiceImpl implements OrderService {
    OrderDao orderDao = new OrderDaoImpl();
    //   CartDao cartDao=new CartDaoImpl();
    OrderDetailDao orderDetailDao = new OrderDetailDaoImpl();
    CartService cartService = new CartServiceImpl();

    @Override
    public Order addOrder(int id, int parseInt) {
        Connection conn = TxUtils.getConn();
        try {
            conn.setAutoCommit(false);
            List<Cart> carts = cartService.findByUid(id);
            double sum = 0;
            for (Cart cart : carts) {
                sum += cart.getMoney();
            }
            Order order = new Order();
            order.setAid(parseInt);
            order.setUid(id);
            order.setMoney(sum);
            order.setStatus(1);
            order.setTime(new Date());
            order.setId(RandomUtils.createActive());
            orderDao.addOrder(order);
            for (Cart cart : carts) {
                OrderDetail orderDetail = new OrderDetail();
                orderDetail.setOid(order.getId());
                orderDetail.setPid(cart.getPid());
                orderDetail.setNum(cart.getNum());
                orderDetail.setMoney(cart.getMoney());
                orderDetailDao.add(orderDetail);
            }
            cartService.clearByUid(id);
            conn.commit();
            return order;
        } catch (Exception e) {
            e.printStackTrace();
            try {
                conn.rollback();
            } catch (Exception e1) {
                e1.printStackTrace();
            }
        } finally {
            TxUtils.remove();
            try {
                conn.setAutoCommit(true);
                conn.close();
            } catch (Exception e2) {
                e2.printStackTrace();
            }

        }
           return null;
    }

    @Override
    public List<Order> select() {
       return orderDao.select();
    }

    @Override
    public void update(String parseInt) {
         orderDao.update(parseInt);
    }

    @Override
    public List<Order> findByName(String toString, List<Object> parmas) {
        return orderDao.findByName(toString,parmas);
    }

}
